﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SJTU.SE.RoughSet.Lib.IO
{
    public class DecisionTableFileInitializer : SJTU.SE.RoughSet.Lib.IO.IDecisionTableFileInitializer
    {
        private List<int[]> mDecisionTableData = new List<int[]>();

        public int RowCount { get; private set; }
        public int ColumnCount { get; private set; }

        public DecisionTableFileInitializer(string FilePath)
        {
            FileInfo fi = new FileInfo(FilePath);
            if (fi.Exists)
            {
                using (StreamReader fileReader = new StreamReader(FilePath))
                {
                    string decisionRowString;
                    int[] rowData;
                    string[] rowStringArray;
                    while (!fileReader.EndOfStream)
                    {
                        decisionRowString = fileReader.ReadLine();
                        rowStringArray = decisionRowString.Split(new char[] { ' ' });

                        //row count + 1
                        this.RowCount++;

                        // check column count
                        if (this.ColumnCount == 0)
                        {
                            this.ColumnCount = rowStringArray.Length;
                        }
                        else if (this.ColumnCount != rowStringArray.Length)
                        {
                            throw new InvalidDataException(string.Format("Column count error! The {0} row has {1} columns",this.RowCount,rowStringArray.Length));
                        }

                        // deall with row data
                        rowData = new int[this.ColumnCount];
                        for(int i=0;i< rowStringArray.Length;i++)
                        {
                            rowData[i] = Int32.Parse(rowStringArray[i]);
                        }
                        this.mDecisionTableData.Add(rowData);
                    }
                }
            }
            else
            {
                throw new FileNotFoundException(FilePath + " not found!");
            }
        }

        public int[][] GetRawData()
        {
            return this.mDecisionTableData.ToArray();
        }
    }
}
